<script setup>
import { RouterLink, RouterView, routerKey } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive, onMounted } from 'vue'
import { default as http, getImageUrl } from '@/utils/request.js';
import { useRouter} from 'vue-router'; //路由器
const router = useRouter(); //获取到 router 对象，用于编程式跳转导航
//跳转到登录页面
// function toOrderView() {
//     router.push("/mycomment");
// }
const active = ref(0);

const onClickLeft = () => router.push("/personal");
// Alt + Shift +F 整理代码格式


// 待付款列表
const beforePayList = reactive([

])

const changeTab = (name, title) => {
  // console.log(name, title);
  getOrderList(name);
}

// console.log("=========订单号",beforePayList.orderNumber)
// 获取付款列表  /user/order?status=0
// const getBeforePayList = (status) => {getOrderList
const getOrderList = (status) => {
  http.get("/user/order", {
    params: {orderState: status}
  }).then((res) => {
      beforePayList.splice(0); 
      res.data.data.list.forEach(order => {
        beforePayList.push(order);
      });
      console.log('获取待付款列表: ', res.data.data.list);
      console.log('beforePayList:', beforePayList);
      // resolve(); // 当获取待收货列表成功后，返回一个解析成功的Promise  
    }).catch(err => {
      reject(err); // 当请求失败时，返回一个请求失败的Promise  
    });
  // // console.log("------------" + user.value);
  // http.get("/user/info").then((response) => {
  //   console.log("获取个人信息= ", response);
  //   console.log("id:", response.data.data.userName);
    

  // }).catch(() => {
  // });
};

// 去支付
const payOrder = (orderNumber) => {
  router.push({name: 'PayDetailView', params: { orderNumber }})
}

// 打开订单

// 打开订单
// /suborder/:orderNumber,
// const router = useRouter();
const toOrder = function (orderNumber) {
    console.log("订单号:", orderNumber);
    // router.push({name: 'suborder', params: { orderNumber }});
    router.push({path: '/suborder/' +orderNumber})
}

// 取消订单
// 删除操作
const handleDelete = (orderNumber) => {

    console.log("------------删除方法");
  // 二次确认删除
  ElMessageBox.confirm(`确定要删除此订单吗？`, '提示', {
    type: 'warning'
  }).then(() => {//用户点击确定按钮
      http.delete("/user/order/"+orderNumber)
        .then((res) => {
          console.log('删除返回值：', res);
          if (res.data.status === 200) {	//修改成功
            ElMessage.success(`取消成功`);
            beforePayList();
          }
        }).catch((err) => {
          console.log('取消失败：', err);
          ElMessage.error(`取消失败`);
        });
    })
    .catch(() => {//点击取消按钮

    });
  
};

// 失效时间
//倒计时
// const time = ref(30 * 60 * 60 * 1000);

let countdown = 0;  

const startCountdown=()=> {  
      const now = new Date();  
      const futureDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); // 24小时后的日期  
      const timeDifference = futureDate - now; // 计算时间差（毫秒）  
      // countdown = Math.floor(timeDifference / 1000); // 将时间差转换为秒数，并存储在countdown中  
      countdown = timeDifference;
      setInterval(() => {  
        countdown--; // 每秒递减1秒  
        if (countdown < 0) {  
          handleDelete(beforePayList.orderNumber);
          clearInterval(); // 倒计时结束后清除定时器  
        }  
      }, 1000); // 每秒执行一次  
    }  
 

onMounted(() => {
  startCountdown();
  // getBeforePayList();
  getOrderList('0');
  // handleDelete(); 
  // 获取个人信息  

});
</script>


<template>
  <van-col span="24" class="nav_bar">
    <van-nav-bar title="待付款" left-text="返回" :fixed="true" left-arrow @click-left="onClickLeft" />
  </van-col>
  <van-cell-group>
    <van-tabs v-model:active="active" style="margin-top: 25px;" @change="changeTab">
      <van-tab title="待付款" name="0"></van-tab>
      <van-tab title="待发货" name="1"></van-tab>
      <van-tab title="待收货" name="2"></van-tab>
      <van-tab title="售 后" name="3" ></van-tab>
      <!-- <van-tab title="待发货" to="/backorder"></van-tab>
      <van-tab title="待收货" to="/aftersend"></van-tab>
      <van-tab title="售 后" to="/returnorder"></van-tab> -->
    </van-tabs>
  </van-cell-group>
  <!-- </div>
  </header>
  <br><br> -->
  <div>
      <div style="color: #c8d175; margin-top: 10px;">
        <van-cell-group inset v-for="bp in beforePayList" @click="toOrder">
          <van-card  :key="bp.orderNumber" :num="bp.amount" :price="bp.orderPrice" :desc="bp.details" :time="time"
            :title="bp.sellName" :thumb="getImageUrl(bp.picture)" style="margin-top: 10px; background-color:  #FFFFE0;"  @click="toOrder(bp.orderNumber)">
            <template #tags>
              <van-tag plain type="primary" style="flex-grow: 1; ">{{bp.goodsName}}</van-tag>
            </template>
            <template #footer>
              <!-- <van-count-down :time="time" style="margin-left: 5px;" /> -->
              <van-row>
                <van-col>
                  距离失效：
                </van-col>
                <van-col>
                  <van-count-down :time="countdown" style="margin-left: 5px;" />
                </van-col>
              </van-row>
              <van-button size="mini" span="8" @click.stop="payOrder(bp.orderNumber)">继续支付</van-button>
              <van-button size="mini" style="margin-left: 15px;" @click.stop="handleDelete(bp.orderNumber)">取消订单</van-button>
            </template>
          </van-card>
        </van-cell-group>
      </div>
    </div>

  <RouterView />
</template>

<style scoped>
header {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 9999;
  line-height: 1.5;
  max-height: 100vh;
}


header {
  line-height: 1.5;
  max-height: 100vh;
}


nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }


  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;
    padding: 1rem 0;
    margin-top: 1rem;
  }
}

.van-field {
  /* 调整每一行边距 */
  padding: 16px 15px;
}

.van-nav-bar {
  color: #d4e09f;
  width: 100%;
}

.full-width-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 10px;
  /* 根据需要调整 */
}

.nav_bar {
  position: relative;
  top: -32px;
  /* left:-32px;
    right: -32px; */
  margin: 2px -32px
}
</style>
